import { 
  CircleBufferGeometry,
  Color,
  DoubleSide,
  Group,
  LineBasicMaterial,
  LineSegments,
  Mesh,
  MeshBasicMaterial,
  PerspectiveCamera, 
  Scene, WebGLRenderer, WireframeGeometry 
} from 'three'
import stats from '../../utils/stats'
import dat from 'dat.gui'

const scene = new Scene()
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
camera.position.set(0, 0, 100)
camera.lookAt(0, 0, 0)

let group = new Group()
let circleGeometry = new CircleBufferGeometry(
  // radius — 圆形的半径，默认值为1
  10, 
  // segments — 分段（三角面）的数量，最小值为3，默认值为8。
  10, 
  // thetaStart — 第一个分段的起始角度，默认为0。（three o'clock position）
  0, 
  // thetaLength — 圆形扇区的中心角，通常被称为“θ”（西塔）。默认值是2*Pi，这使其成为一个完整的圆。
  Math.PI * 2
)
const planeMaterial = new MeshBasicMaterial({
  color: 0xff9900, 
  side: DoubleSide
})
let lineWireframe = new WireframeGeometry(circleGeometry)
let line = new LineSegments(lineWireframe)
let plane = new Mesh(circleGeometry, planeMaterial)

group.add(plane)
group.add(line)

scene.add(group)

const controls = {
  radius: circleGeometry.parameters.radius,
  segments: circleGeometry.parameters.segments,
  thetaStart: circleGeometry.parameters.thetaStart,
  thetaLength: Math.PI * 2,
  color: planeMaterial.color.getStyle(),
  redraw() {
    // 生成新几何体
    let newGeometry = new CircleBufferGeometry(
      this.radius, 
      ~~this.segments, // 切记为整数
      this.thetaStart, 
      this.thetaLength
    )

    ;(group.children[0] as Mesh).geometry.dispose()
    ;(group.children[1] as Mesh).geometry.dispose()

    ;(group.children[0] as Mesh).geometry = newGeometry;
    (group.children[1] as Mesh).geometry = new WireframeGeometry(newGeometry);
  }
}

const gui = new dat.GUI()
gui.addColor(controls, 'color').onChange(e => {
  planeMaterial.color.set(new Color(e))
})
gui.add(controls, 'radius', 0, 40).onChange(e => controls.redraw())
gui.add(controls, 'segments', 1, 100).onChange(e => controls.redraw())
gui.add(controls, 'thetaLength', 0, Math.PI*2).onChange(e => {
  console.log(e/Math.PI)
  controls.redraw()
})

const renderer = new WebGLRenderer({ antialias: true })
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setClearColor(0x000000)

document.body.appendChild(renderer.domElement)

function render() {
  stats.update()

  group.rotation.y += 0.01

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}

render()